<template>
  <div ref="attendanceRulesRef" class="access-control-rules-box">
    <div class="access-control-main-box">
      <list-comp
        ref="studentRef"
        :access-control-rules-ref="attendanceRulesRef"
        :is-update="isUpdate"
        :is-remove-val="isRemove"
        @deletePeriodVal="deletePeriodVal"
        @addPeriodVal="addPeriodVal"
        @isUpdate="isUpdateFunc"
        @isRemove="isRemoveFunc"
      ></list-comp>
    </div>
    <div class="access-control-btn-box">
      <!-- <div class="flex items-center justify-center" @click="cancle">取消</div> -->
      <!-- <div class="flex items-center justify-center" @click="save">保存</div> -->
      <a-button class="btn" @click="cancle">取消</a-button>
      <a-button class="btn sure" type="primary" :loading="isLoading" @click="save">保存</a-button>
    </div>
    <!--取消返回 提示框 -->
    <my-dialog
      :dialog-state="cancelLamp.visible"
      :dialog-title="cancelLamp.title"
      :dialog-width="cancelLamp.width"
      :show-cancel="true"
      :icon-type="cancelLamp.iconType"
      @handleCancel="cancelLamp.visible = false"
      @handleOk="onCancelLampLamp"
    >
      <template v-slot:location>
        <div class="checkOutStyle">
          <img src="@/assets/images/accommodation/drawable-xxxhdpi_popu_icon_warn.png" alt="" />
          <span>规则未保存，是否确认离开？</span>
        </div>
      </template>
    </my-dialog>
    <a-modal
      v-if="visibles"
      v-model:visible="visibles"
      :footer="null"
      :mask-closable="false"
      width="340px"
      title="温馨提示"
      @cancel="hideModal"
      @ok="hideModal"
    >
      <div class="modal-box">
        <div class="img">
          <img :src="errImg" alt="" />
        </div>
        <div class="text"
          >本次创建成功{{ state.successNumber }}，失败{{ state.failureNumber }}，
          <a href="javascript:;" @click="downLoad">点击此处</a>查看考勤组创建失败原因.xls
        </div>
        <div class="btn">
          <a-button class="modal-btn" type="primary" @click="hideModal">我知道了</a-button>
        </div>
      </div>
    </a-modal>
    <a-modal
      v-if="isChangeVisible"
      v-model:visible="isChangeVisible"
      :footer="null"
      :mask-closable="false"
      width="400px"
      title="温馨提示"
      @ok="sureModal"
    >
      <div class="modal-box">
        <div class="box-text">
          <img :src="IconImg" alt="" class="icons" />
          <span>请注意，时间规则修改将在第二天生效。</span>
        </div>
        <div class="tips">今日仍按照原规则考勤</div>
        <div class="btn">
          <a-button class="modal-btn" type="primary" @click="sureModal">我知道了</a-button>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, watch, defineEmits, computed, onMounted, defineExpose } from 'vue';
import { message } from 'ant-design-vue';
import { useStore } from 'vuex';
import { getRgba } from '@/utils/validate.js';
let emits = defineEmits(['cancelAccessControlRules', 'skipIndex']);
import MyDialog from '@/components/dialog/index.vue';
import ListComp from './attendanceList.vue';
import { saveClockGroup, exportCauseFailure } from '@/api/attendance';
// 保存时间组(添加和修改)
const store = useStore();
const studentRef = ref(null);
const attendanceRulesRef = ref(null);
const visibles = ref(false);
const isUpdate = ref(false);
const isChangeVisible = ref(false);
const changeObj = ref({});
const errImg = ref(require('@/assets/images/popup_img_daoru@2x.png'));
const IconImg = ref(require('@/assets/images/icon_xinxitishi_nor@2x.png'));
onMounted(() => {});
const cancle = () => {
  let ruleVal = JSON.parse(sessionStorage.getItem('ruleList'));
  let ruleLists = JSON.parse(JSON.stringify(studentRef.value.ruleList));
  console.log(JSON.stringify(ruleVal) === JSON.stringify(ruleLists));
  if (JSON.stringify(ruleVal) === JSON.stringify(ruleLists)) {
    store.commit('user/setDoorRule', 0);
    cancelLamp.value.visible = false;
    isUpdate.value = true;
    emits('skipIndex');
  } else {
    cancelLamp.value.visible = true;
  }
};

// 确认离开按钮
const onCancelLampLamp = () => {
  console.log('wqwqwqwq');
  store.commit('user/setDoorRule', 0);
  cancelLamp.value.visible = false;
  isUpdate.value = true;
  emits('skipIndex');
};

let isUpdateFunc = data => {
  isUpdate.value = data;
};
let isRemoveFunc = data => {
  isRemove.value = data;
};
// 删除时段的id数组
const removeId = ref([]);
let deletePeriodVal = data => {
  console.log(data);
  removeId.value = data;
};
// 新增时段的id数组
const addPeriod = ref([]);
let addPeriodVal = data => {
  console.log(data, 'data-*-*-*-*-*-');
  addPeriod.value = data;
};
let state = reactive({
  failureList: [], // 失败问题
  failureNumber: null, // 失败条数
  successNumber: null // 成功条数
});
function some(arr) {
  let some = [];
  arr.forEach(el => {
    if (el.id && el.id !== null && el.id !== undefined) {
      if (!some.some(e => e.id === el.id)) {
        some.push(el);
      }
    } else {
      some.push(el);
    }
  });
  return some;
}
function upData() {
  studentRef.value.GetTimeGroupList(0);
}
let isLoading = ref(false);
const save = () => {
  console.log('qnimd', studentRef.value.ruleList);
  console.log(studentRef.value);
  if (studentRef.value.ruleList.length <= 0) {
    message.error(`请创建考勤规则`);
    return;
  }
  let isErr = false;
  let obj = {
    rules: [],
    deletePeriodIds: removeId.value.length > 0 ? removeId.value : [],
    addPeriod: addPeriod.value.length > 0 ? addPeriod.value : []
  };
  if (hasDuplicates(studentRef.value.ruleList)) {
    message.error(`生效范围 选择重复`);
    isErr = true;
    return false;
  }

  studentRef.value.ruleList.forEach((item, index) => {
    console.log(item, index, '/-/-/-/-/');
    if (!item.name) {
      message.error(`第${index + 1}条 规则名称 未填写`);
      item.isErr = true;
      isErr = true;
      return false;
    }
    if (item.effectiveScope === '') {
      message.error(`第${index + 1}条 生效范围 未选择`);
      item.isErr = true;
      isErr = true;
      return false;
    }
    item.periodRule.forEach((item1, index1) => {
      if (item1.timeArr.length === 0) {
        item.isErr = true;
        isErr = true;
        message.error(`第${index + 1}条考勤组 第${index1 + 1}条 考勤时间 未选择`);
        return;
      }
      if (item1.name === '') {
        item.isErr = true;
        isErr = true;
        message.error(`第${index + 1}条考勤组 第${index1 + 1}条 考勤名称 未选择`);
        return;
      }
    });
    let objData = {};
    objData.effectiveScope = item.effectiveScopeList;
    objData.id = item.id;
    objData.name = item.name;
    objData.periodRule = JSON.stringify(item.periodRule);
    obj.rules.push(objData);
  });
  if (isErr) {
    return;
  }

  let ruleVal = JSON.parse(sessionStorage.getItem('ruleList'));
  let ruleLists = JSON.parse(JSON.stringify(studentRef.value.ruleList));
  if (ruleVal.length === 1 && ruleVal[0].id === '') {
    saveData(obj);
  } else if (sessionStorage.getItem('ruleList') === JSON.stringify(studentRef.value.ruleList)) {
    saveData(obj);
  } else {
    // debugger;
    let isRule = false;
    for (let i = 0; i < ruleLists.length; i++) {
      for (let j = 0; j < ruleVal.length; j++) {
        let rule1 = ruleLists[i].periodRule;
        let rule2 = ruleVal[j].periodRule;
        if (isRule) {
          break;
        }
        if (ruleLists.length === 1 && ruleLists[0].id === '') {
          saveData(obj);
          break;
        } else {
          isRule = compareData(rule1, rule2, obj);
        }
      }
    }

    if (!isRule) {
      saveData(obj);
    }
  }
};

function hasDuplicates(array) {
  let values = {};
  let valueObj = {};
  for (let i = 0; i < array.length; i++) {
    let value = array[i].effectiveScope;
    let item = [];
    if (array[i].effectiveScopeList !== '-1') {
      for (let k = 0; k < value.length; k++) {
        const element = value[k];
        item = element.slice(0, 2);
        if (valueObj[item]) {
          return true;
        }
      }
    }
    if (i > 0 && array[i].effectiveScopeList === '-1') {
      return true;
    }

    if (values[value]) {
      return true;
    }
    valueObj[item] = true;
    values[value] = true;
  }
  return false;
}

function compareData(rule1, rule2, obj) {
  let isRule = null;
  for (let k = 0; k < rule1.length; k++) {
    if (!rule1[k] || !rule2[k]) {
      continue;
    } else if (rule1[k].name !== rule2[k].name || rule1[k].period !== rule2[k].period) {
      isChangeVisible.value = true;
      changeObj.value = obj;
      isRule = true;
      break;
    }
  }
  return isRule;
}
let isRemove = ref(false);
function saveData(obj) {
  if (!isLoading.value) {
    isLoading.value = true;
    saveClockGroup(obj)
      .then(res => {
        console.log('新增', res);
        if (res.data.code === 200) {
          let data = res.data.data;
          if (data.failureNumber === 0) {
            message.success('保存成功');
            setTimeout(() => {
              emits('skipIndex');
              isLoading.value = false;
              addPeriod.value = [];
              removeId.value = [];
              isUpdate.value = true;
            }, 1000);
          } else {
            state.failureNumber = data.failureNumber;
            state.successNumber = data.successNumber;
            state.failureList = data.failureList;
            visibles.value = true;
            isLoading.value = false;
          }
        } else {
          message.error(res.data.msg);
          setTimeout(() => {
            isLoading.value = false;
          }, 1000);
        }
      })
      .catch(() => {
        message.error('系统内部异常');
        setTimeout(() => {
          isLoading.value = false;
        }, 1000);
      })
      .finally(() => {
        isRemove.value = true;
      });
  }
}

let sureModal = () => {
  isChangeVisible.value = false;
  saveData(changeObj.value);
};
//  关闭提示框
let hideModal = () => {
  visibles.value = false;
  isUpdate.value = true;
  addPeriod.value = [];
  removeId.value = [];
  emits('skipIndex');
};
// 导出创建规则错误
let downLoad = () => {
  let obj = {
    failureList: state.failureList
  };
  exportCauseFailure(obj).then(res => {
    console.log(res);
    const link = document.createElement('a');
    let blob = new Blob([res.data], { type: 'application/vnd.ms-excel' });
    link.style.display = 'none';
    // 设置连接
    link.href = URL.createObjectURL(blob);
    link.download = '考勤组创建失败原因.xlsx';
    document.body.appendChild(link);
    // 模拟点击事件
    link.click();
  });
};
function emptyAllDel() {
  studentRef.value.emptyDel();
}
// 取消规则按钮
const cancelLamp = ref({
  title: '温馨提示',
  visible: false,
  width: '328px',
  iconType: 'default'
});

defineExpose({
  upData,
  emptyAllDel
});
// 定义颜色变量
const setStyles = computed(() => {
  return {
    '--primaryColor': store.state.user.primaryColor,
    primaryColor: store.state.user.primaryColor,
    backgroundColor: getRgba(store.state.user.primaryColor, 0.1)
  };
});
</script>

<style lang="less" scoped>
@import './accessControlRules.less';
.access-control-btn-box {
  display: flex;
  justify-content: center;
  padding: 16px 0;
  .btn {
    width: 116px;
    height: 36px;
    font-size: 14px;
    font-weight: 400;
  }
  .sure {
    margin-left: 24px;
  }
}

::v-deep(.micro-dormitory-modal-header) {
  border-bottom: none;
  padding-bottom: 0;
}
::v-deep(.micro-dormitory-modal-title) {
  font-size: 18px;
}
.modal-box {
  .img {
    img {
      margin: 0 auto;
      width: 126px;
    }
  }
  .text {
    margin-top: 16px;
    width: 292px;
    height: 80px;
    background: #f8f8f8;
    border-radius: 4px;
    padding: 16px;
  }
  .box-text {
    background: #f8f8f8;
    border-radius: 4px;
    padding: 12px 14px;
    display: flex;
    align-items: center;

    span {
      color: #666;
      font-size: 16px;
    }
    .icons {
      width: 24px;
      height: 24px;
      display: inline-block;
      margin-right: 8px;
    }
  }
  .tips {
    margin-top: 8px;
    font-size: 14px;
    font-family: Source Han Sans CN, Source Han Sans CN-Regular;
    font-weight: 400;
    color: #999999;
    line-height: 22px;
  }
  .btn {
    margin-top: 16px;
    text-align: right;
  }
  .modal-btn {
    width: 88px;
    height: 32px;
    color: #ffffff;
    font-size: 14px;
    font-weight: 400;
    color: #ffffff;
    line-height: 22px;
    border-radius: 4px;
  }
}
.access-control-main-box {
  padding: 0 24px;
}
:deep(.micro-dormitory-message) {
  & > div {
    align-items: center;
  }
}
</style>
